<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单证名称" prop="documentName">
        <el-input
          v-model="queryParams.documentName"
          placeholder="请输入单证名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单证类型" prop="documentTypeId">
        <el-select v-model="queryParams.documentTypeId" placeholder="请选择单证类型" clearable>
          <el-option
            v-for="dict in documentTypeOptions"
            :key="dict.typeId"
            :label="dict.typeName"
            :value="dict.typeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关联单号" prop="referenceNo">
        <el-input
          v-model="queryParams.referenceNo"
          placeholder="请输入关联单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传人" prop="uploadBy">
        <el-input
          v-model="queryParams.uploadBy"
          placeholder="请输入上传人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleUpload"
          v-hasPermi="['fiscale:document:upload']"
        >上传单证</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="documentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单证ID" align="center" prop="documentId" />
      <el-table-column label="单证名称" align="center" prop="documentName" :show-overflow-tooltip="true" />
      <el-table-column label="单证类型" align="center" prop="documentTypeName" />
      <el-table-column label="关联单号" align="center" prop="referenceNo" />
      <el-table-column label="文件类型" align="center" prop="fileType" />
      <el-table-column label="文件大小(KB)" align="center" prop="fileSize">
        <template slot-scope="scope">
          {{ (scope.row.fileSize / 1024).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="上传人" align="center" prop="uploadBy" />
      <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.uploadTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['fiscale:document:download']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="handleRelate(scope.row)"
            v-hasPermi="['fiscale:document:relate']"
            v-if="isCoreDocument(scope.row.documentTypeId)"
          >关联</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fiscale:document:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 上传单证对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="500px" append-to-body @close="handleUploadCancel">
      <el-form ref="uploadForm" :model="upload.form" :rules="upload.rules" label-width="80px">
        <el-form-item label="单证类型" prop="documentTypeId">
          <el-select v-model="upload.form.documentTypeId" placeholder="请选择单证类型">
            <el-option
              v-for="dict in documentTypeOptions"
              :key="dict.typeId"
              :label="dict.typeName"
              :value="dict.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联单号" prop="referenceNo">
          <el-input v-model="upload.form.referenceNo" placeholder="请输入关联单号" />
        </el-form-item>
        <el-form-item label="单证文件">
          <el-upload
            ref="uploadFile"
            :limit="1"
            accept=".pdf,.jpg,.jpeg,.png"
            :action="upload.url"
            :headers="upload.headers"
            :data="uploadData"
            :file-list="upload.fileList"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-error="handleFileError"
            :auto-upload="false"
            :before-upload="beforeFileUpload"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传pdf/jpg/png文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="handleUploadCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看单证对话框 -->
    <el-dialog :title="view.title" :visible.sync="view.open" width="500px" append-to-body>
      <el-form :model="view.form" label-width="80px">
        <el-form-item label="单证类型">
          <el-input v-model="view.form.documentTypeName" readonly />
        </el-form-item>
        <el-form-item label="单证名称">
          <el-input v-model="view.form.documentName" readonly />
        </el-form-item>
        <el-form-item label="关联单号">
          <el-input v-model="view.form.referenceNo" readonly />
        </el-form-item>
        <el-form-item label="文件类型">
          <el-input v-model="view.form.fileType" readonly />
        </el-form-item>
        <el-form-item label="文件大小">
          <el-input v-model="view.form.fileSizeDisplay" readonly />
        </el-form-item>
        <el-form-item label="上传人">
          <el-input v-model="view.form.uploadBy" readonly />
        </el-form-item>
        <el-form-item label="上传时间">
          <el-input v-model="view.form.uploadTimeDisplay" readonly />
        </el-form-item>
        <el-form-item label="单证文件">
          <el-input v-model="view.form.fileName" readonly />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="view.open = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 关联单证对话框 -->
    <el-dialog :title="relate.title" :visible.sync="relate.open" width="800px" append-to-body>
      <el-table
        v-loading="relate.loading"
        :data="relate.documentList"
        @selection-change="handleRelateSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="单证名称" align="center" prop="documentName" />
        <el-table-column label="单证类型" align="center" prop="documentTypeName" />
        <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.uploadTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRelateForm">确 定</el-button>
        <el-button @click="relate.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDocument, deleteDocument, uploadDocument, batchAddDocumentRelations } from "@/api/fiscale/document";
import { listDocumentType } from "@/api/fiscale/documentType";
import { getToken } from "@/utils/auth";

export default {
  name: "Document",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单证表格数据
      documentList: [],
      // 单证类型选项
      documentTypeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        documentName: null,
        documentTypeId: null,
        referenceNo: null,
        uploadBy: null
      },
      // 上传参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/fiscale/document/upload",
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 文件列表
        fileList: [],
        // 加载状态
        loading: false,
        // 表单参数
        form: {
          documentTypeId: null,
          referenceNo: null
        },
        // 表单校验
        rules: {
          documentTypeId: [
            { required: true, message: "单证类型不能为空", trigger: "change" }
          ]
        }
      },
      // 查看参数
      view: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 表单参数
        form: {
          documentName: "",
          documentTypeName: "",
          referenceNo: "",
          fileType: "",
          fileSizeDisplay: "",
          uploadBy: "",
          uploadTimeDisplay: "",
          fileName: "",
          fileUrl: ""
        }
      },
      // 关联参数
      relate: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 遮罩层
        loading: false,
        // 当前单证ID
        documentId: null,
        // 单证列表
        documentList: [],
        // 选中数组
        selectedDocuments: []
      }
    };
  },
  computed: {
    // 上传数据计算属性
    uploadData() {
      return {
        documentTypeId: this.upload.form.documentTypeId,
        referenceNo: this.upload.form.referenceNo
      };
    }
  },
  created() {
    this.getList();
    this.getDocumentTypeOptions();
  },
  methods: {
    /** 查询单证列表 */
    getList() {
      this.loading = true;
      listDocument(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.documentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询单证类型下拉选项 */
    getDocumentTypeOptions() {
      listDocumentType().then(response => {
        this.documentTypeOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.upload.open = false;
      this.resetUploadForm();
    },
    // 表单重置
    resetUploadForm() {
      this.upload.form = {
        documentTypeId: null,
        referenceNo: null
      };
      // 确保DOM元素已经渲染完成后再调用clearFiles
      this.$nextTick(() => {
        if (this.$refs.uploadFile) {
          this.$refs.uploadFile.clearFiles();
        }
        if (this.$refs.uploadForm) {
          this.$refs.uploadForm.resetFields();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.documentId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 上传按钮操作 */
    handleUpload() {
      console.log('点击上传按钮');
      this.resetUploadForm();
      this.upload.open = true;
      this.upload.title = "上传单证";
      console.log('对话框状态:', this.upload.open);
    },
    // 处理上传取消
    handleUploadCancel() {
      this.upload.open = false;
      this.resetUploadForm();
    },
    // 文件上传前的钩子
    beforeFileUpload(file) {
      const isValidType = file.type === 'application/pdf' || file.type.startsWith('image/');
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isValidType) {
        this.$modal.msgError('上传文件只能是 PDF/JPG/PNG 格式!');
        return false;
      }
      if (!isLt10M) {
        this.$modal.msgError('上传文件大小不能超过 10MB!');
        return false;
      }
      return true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.loading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.loading = false;
      console.log('上传响应:', response);
      if (response.code === 200) {
        this.upload.open = false;
        // 使用$nextTick确保在DOM更新后执行
        this.$nextTick(() => {
          if (this.$refs.uploadFile) {
            this.$refs.uploadFile.clearFiles();
          }
        });
        this.$modal.msgSuccess("上传成功");
        this.getList();
      } else {
        this.$modal.msgError(response.msg || "上传失败");
      }
    },
    // 文件上传失败处理
    handleFileError(err, file, fileList) {
      this.upload.loading = false;
      console.error('上传错误:', err);
      this.$modal.msgError("上传失败：" + (err.message || "未知错误"));
    },
    // 提交上传表单
    submitFileForm() {
      // 首先检查文件是否已上传
      const fileList = this.$refs.uploadFile.uploadFiles;
      if (fileList.length === 0) {
        this.$modal.msgError("请上传文件");
        return;
      }
      
      // 验证表单其他字段
      this.$refs.uploadForm.validate(valid => {
        if (valid) {
          // 检查必填字段
          if (!this.upload.form.documentTypeId) {
            this.$modal.msgError("请选择单证类型");
            return;
          }
          
          // 设置上传参数
          this.upload.loading = true;
          
          // 提交上传
          this.$refs.uploadFile.submit();
        }
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.view.title = "查看单证 - " + row.documentName;
      
      // 从文件URL中提取文件名
      let fileName = row.documentName;
      if (row.fileUrl) {
        const urlParts = row.fileUrl.split('/');
        const lastPart = urlParts[urlParts.length - 1];
        if (lastPart && lastPart.includes('.')) {
          fileName = decodeURIComponent(lastPart);
        }
      }
      
      this.view.form = {
        documentName: row.documentName,
        documentTypeName: row.documentTypeName,
        referenceNo: row.referenceNo || "-",
        fileType: row.fileType,
        fileSizeDisplay: (row.fileSize / 1024).toFixed(2) + " KB",
        uploadBy: row.uploadBy,
        uploadTimeDisplay: this.parseTime(row.uploadTime),
        fileName: fileName,
        fileUrl: row.fileUrl
      };
      this.view.open = true;
    },
    /** 关联按钮操作 */
    handleRelate(row) {
      this.relate.documentId = row.documentId;
      this.relate.title = "关联单证 - " + row.documentName;
      this.relate.open = true;
      this.relate.loading = true;
      
      // 查询可关联的单证列表
      listDocument({
        documentTypeId: null,
        excludeDocumentId: row.documentId
      }).then(response => {
        this.relate.documentList = response.rows;
        this.relate.loading = false;
      });
    },
    // 关联单证多选框选中数据
    handleRelateSelectionChange(selection) {
      this.relate.selectedDocuments = selection.map(item => item.documentId);
    },
    // 提交关联表单
    submitRelateForm() {
      if (this.relate.selectedDocuments.length === 0) {
        this.$modal.msgError("请选择要关联的单证");
        return;
      }
      
      // 调用API添加关联
      batchAddDocumentRelations(this.relate.documentId, this.relate.selectedDocuments).then(response => {
        this.$modal.msgSuccess("关联成功");
        this.relate.open = false;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const documentIds = row.documentId || this.ids;
      this.$modal.confirm('是否确认删除单证编号为"' + documentIds + '"的数据项？').then(function() {
        return deleteDocument(documentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 判断是否是核心单证 */
    isCoreDocument(documentTypeId) {
      // 这里可以根据实际业务逻辑判断哪些单证类型是核心单证
      // 示例：报关单、发票等是核心单证
      const coreTypes = ['CUSTOMS_DECLARATION', 'INVOICE'];
      const type = this.documentTypeOptions.find(item => item.typeId === documentTypeId);
      return type && coreTypes.includes(type.typeCode);
    }
  }
};
</script>

<style scoped>
.el-upload__tip {
  margin-top: 7px;
  color: #606266;
  font-size: 12px;
}
</style>